﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Loki.UI
{
    public class Validator<TValue> : IValidator
    {
        private Func<TValue> _Getter;

        public Validator(Func<TValue> P_Getter)
        {
            _Getter = P_Getter;
            Rules = new Dictionary<IValidationRule, string>();
        }

        public void AddRule(IValidationRule P_Rule, string P_ErrorMessage)
        {
            Rules[P_Rule] = P_ErrorMessage;
        }

        public bool Validate()
        {
            var L_Value = _Getter();
            return Rules.Keys.All(x => x.Validate(L_Value));
        }

        public string GetErrorMessage()
        {
            var L_Value = _Getter();
            var L_Error = Rules.FirstOrDefault(x => !x.Key.Validate(L_Value));
            if (L_Error.Key != null)
            {
                return L_Error.Value;
            }
            else
            {
                return string.Empty;
            }
        }

        protected Dictionary<IValidationRule, string> Rules { get; private set; }
    }
}
